var API = require('API').vehicle_model;
var popup =
        '<div class="picker-item truncate-item" ng-click="truncate()">[ X ]</div>'
        + '<div class="picker-item" ng-repeat="v in data|orderBy:[\'sn\'] | filter:picker_filter" ng-click=\'submit(v)\'>'
        + '{{displayName(v)}}'
        + '</div>';

module.exports = function () {
    return {
        restrict: 'E',
        scope   : {
            vehicleModel: "="
        },
        template: '<div class="picker-content">'
        + '<div class="picker-input">'
        + '<div class="display" style="width:100%;" ng-show="!show">{{displayName()}}</div>'
        + '<input class="input" ng-show ="show" type="text" style="width:100%;"  placeholder="查询..." ng-model="picker_filter.$">'
        + '</div>'
        + '<div ng-show="show" class="vm-picker-menu">'
        + popup
        + '</div>'
        + '</div>',

        replace   : true,
        controller: ['$scope', '$element', '$timeout', function ($scope, $element, $timeout) {


            $scope.data = [];
            $scope.show = false;
            $scope.picker_filter = {};
            var format = $element.attr('format') || "brand | model | version | sn | msrp";

            var $overlay = $('<div/>').css({
                height    : '100%',
                width     : '100%',
                position  : 'fixed',
                top       : 0,
                left      : 0,
                background: "rgba(255,255,255,0)",
                "z-index" : "1"
            }).click(function () {
                $scope.$apply(function () {
                    close_menu();
                });
            });

            var close_menu = function () {
                $scope.show = false;
                $overlay.detach();
            };

            var items = [];
            $scope.selected = -1;
            var reset_items = function () {
                $scope.selected = -1;
                items = $element.find('.picker-item').hover(function () {
                    items.removeClass('selected');
                    $(this).addClass('selected');
                }, function () {
                    $(this).removeClass('selected');
                });
            };
            var $input = $element.find('.input');
            var $display = $element.find('.display');

            $scope.displayName = function (vm) {
                var d = vm || $scope.vehicleModel;
                if (!d || Object.keys(d).length == 0)return "请选择车型";
                var ret = format.slice(0);
                ret = ret.replace(/sn/g, d.sn);
                ret = ret.replace(/brand/g, d.brand);
                ret = ret.replace(/model/g, d.model);
                ret = ret.replace(/version/g, d.version);
                ret = ret.replace(/msrp/g, d.msrp);
                return ret;
            };

            $display.click(function () {
                API.all(function (list) {
                    $scope.$apply(function () {
                        $scope.data = list;
                        $scope.show = true;
                        $overlay.appendTo($element.find('.picker-menu'));
                        $timeout(function () {
                            reset_items();
                            $input[0].focus();
                        });
                    });
                });
            });
            var i = 0;

            $input.keydown(function (e) {
                var keyCode = e.keyCode;

                if (keyCode == 38) { // down
                    $(items).removeClass('selected');
                    if ($scope.selected !== -1) {
                        $scope.selected--;
                    }
                    if ($scope.selected == -1) {
                        //clear all the style
                    } else {
                        $(items[$scope.selected]).addClass('selected');
                    }
                    if (i <= 30) {
                        i = 0;
                        $(".picker-menu").scrollTop(i);
                    }else{
                        i = i - 30;
                        $(".picker-menu").scrollTop(i);
                    }
                }
                else if (keyCode == 40) {//up
                    if ($scope.selected < items.length - 1) {
                        $scope.selected++;
                    }
                    $(items).removeClass('selected');
                    $(items[$scope.selected]).addClass('selected');

                    if ($scope.selected >= 3) {
                        if (i >= $(items).length*60 - 120) {
                            $(".picker-menu").scrollTop(i);
                        }else{
                            $(".picker-menu").scrollTop(i);
                            i = i + 30;
                        }
                    }
                }
                else if (keyCode == 13) {
                    //enter
                    if ($scope.selected > -1) {
                        $(items[$scope.selected]).trigger('click')
                    }
                    else {
                        //close the menu and leave the same
                        $scope.$apply(function () {
                            close_menu();
                        })
                    }
                    return;
                }
                else if (keyCode == 27) {
                    $scope.$apply(function () {
                        close_menu();
                    })
                }
                else {
                    $scope.$apply(function () {
                        $timeout(function () {
                            reset_items();
                        });
                    });
                }
            });

            $scope.truncate = function () {
                $scope.vehicleModel = {};
                close_menu();
            };

            $scope.submit = function (v) {
                $scope.vehicleModel = v;
                close_menu();
            };
        }]
    }
};